package com.jwgf.smarowindingmachine_unity.ui;

import com.jwgf.common.ViewCache;
import com.jwgf.protocolstack.ProtocolStack;
import com.jwgf.protocolstack.CommunicationStateListener.WriteFailedListener;
import com.jwgf.protocolstack.CommunicationStateListener.WriteSucceedListener;
import com.jwgf.smarowindingmachine_unity.R;
import com.jwgf.smarowindingmachine_unity.logic.MachineParameterSharedPreference;
import com.jwgf.smarowindingmachine_unity.logic.SmaroWindingMachineDataAccessRules;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class ParameterSettingDofferParameterFragment extends BaseFragment
        implements OnFocusChangeListener, OnEditorActionListener, OnClickListener, WriteFailedListener, WriteSucceedListener {
    public static final String fragmentTag = "ParameterSettingDofferParameterFragment";

    private MachineParameterSharedPreference sp = MachineParameterSharedPreference.getInstance();

    private TextView moving_speed_value;

    private EditText tube_left_tail_value;

    private ImageButton moving_speed_btn;    //D213


    private EditText initial_position_edit;    //D211
    private EditText start_num_edit;
    private EditText end_num_edit;            //D214

    private View thisView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = ViewCache.getInstance().getView(R.layout.fragment_parameter_setting_doffer_parameter);
        thisView = v;
        initialViews(thisView);
        updateViews();
        return v;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            SmaroWindingMachineActivity.canHandStack.unregisterWriteFailedListener(this);
            SmaroWindingMachineActivity.canHandStack.unregisterWriteSucceedListener(this);
        }
    }

    private void initialViews(View v) {
        initial_position_edit = initEdittextOnCreate(R.id.initial_position_value);
        start_num_edit = initEdittextOnCreate(R.id.start_num_value);
        end_num_edit = initEdittextOnCreate(R.id.end_num_value);
        end_num_edit.setText(sp.getValue(0x29, 01));
        moving_speed_btn = (ImageButton) v.findViewById(R.id.moving_speed_btn);
        moving_speed_btn.setOnClickListener(this);

        moving_speed_value = (TextView) v.findViewById(R.id.moving_speed_value);

        tube_left_tail_value = initEdittextOnCreate(R.id.tube_left_tail_value);
    }

    private void updateViews() {
        initial_position_edit.setText(sp.getValue(MachineParameterSharedPreference.INITIAL_POSITION, "0"));
        start_num_edit.setText(sp.getValue(MachineParameterSharedPreference.DOFFER_START_NUM, "1"));
        end_num_edit.setText(sp.getValue(MachineParameterSharedPreference.END_NUM, "72"));
        tube_left_tail_value.setText(sp.getValue(String.valueOf(0x39) + "-" + 0));
        if (sp.getValue(MachineParameterSharedPreference.MOVING_SPEED, "0").equals("0")) {
            moving_speed_value.setText(R.string.fast);
        } else if (sp.getValue(MachineParameterSharedPreference.MOVING_SPEED, "0").equals("1")) {
            moving_speed_value.setText(R.string.slow);
        } else {
            moving_speed_value.setText(R.string.mid);
        }

    }

    private EditText initEdittextOnCreate(int id) {
        EditText editText = (EditText) thisView.findViewById(id);
        editText.setSelectAllOnFocus(true);
        editText.setOnFocusChangeListener(this);
        editText.setOnEditorActionListener(this);
        editText.setBackgroundDrawable(null);
        return editText;
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            SmaroWindingMachineActivity.canHandStack.registerWriteFailedListener(this);
            SmaroWindingMachineActivity.canHandStack.registerWriteSucceedListener(this);
            String strValue = v.getText().toString();
            if (strValue.equals("")) {
                return false;
            }
            boolean isValid = false;
            String key = "";
            String value = v.getText().toString();
            switch (v.getId()) {
                case R.id.initial_position_value:
                    isValid = SmaroWindingMachineDataAccessRules.getInstance().isBetween(MachineParameterSharedPreference.INITIAL_POSITION, strValue);
                    key = MachineParameterSharedPreference.INITIAL_POSITION;
                    if (isValid) {
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(sp.createCanCmd75(0x75, 0x01, 501, strValue));
                        sp.setValue(key, strValue);
                    }
                    break;

                case R.id.start_num_value:
                    isValid = SmaroWindingMachineDataAccessRules.getInstance().isBetween(MachineParameterSharedPreference.DOFFER_START_NUM, strValue);
                    key = MachineParameterSharedPreference.DOFFER_START_NUM;
                    if (isValid) {
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(sp.createCanCmd75(0x75, 0x01, 515, strValue));
                        sp.setValue(key, strValue);
                    }
                    break;

                case R.id.end_num_value:
                    isValid = SmaroWindingMachineDataAccessRules.getInstance().isBetween(MachineParameterSharedPreference.END_NUM, strValue);
                    key = MachineParameterSharedPreference.END_NUM;
                    if (isValid) {
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(sp.createCanCmd75(0x75, 0x01, 508, strValue));
                        sp.setValue(key, strValue);
                    }
                    break;
                case R.id.tube_left_tail_value:
                    isValid = SmaroWindingMachineDataAccessRules.getInstance().isBetween(String.valueOf(0x39) + "-" + 0, strValue);
                    key = String.valueOf(0x39) + "-" + 0;
                    if (isValid) {
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(sp.getBroadcast());
                        SmaroWindingMachineActivity.canHandStack
                                .putPriorityCmd(sp.createCanCmdNoGroup(0x39, 0x00, String.valueOf(strValue)));
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(sp.releaseBroadcast());
                        WaitProgressDialog.show(getActivity());
                    }
                    break;
                default:
                    break;
            }
            if (!isValid) {
                String max = SmaroWindingMachineDataAccessRules.getInstance().getDataAccessRule(key).getMax();
                String min = SmaroWindingMachineDataAccessRules.getInstance().getDataAccessRule(key).getMin();
                String warning = getResources().getString(R.string.range_warning);
                warning = String.format(warning, min, max);
                WarningDialog.show(getActivity(), warning);
                updateViews();
            }
        }
        return false;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();
        switch (id) {
            case R.id.initial_position_value:
                if (!hasFocus) {
                    initial_position_edit.setText(
                            sp.getValue(MachineParameterSharedPreference.INITIAL_POSITION, "0"));
                }
                break;
            case R.id.start_num_value:
                if (!hasFocus) {
                    start_num_edit.setText(
                            sp.getValue(MachineParameterSharedPreference.DOFFER_START_NUM, "1"));
                }
                break;
            case R.id.end_num_value:
                if (!hasFocus) {
                    end_num_edit.setText(
                            sp.getValue(MachineParameterSharedPreference.END_NUM, "72"));
                }
                break;

            case R.id.tube_left_tail_value:
                if (!hasFocus) {
                    tube_left_tail_value.setText(sp.getValue(String.valueOf(0x39) + "-" + 0));
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onClick(View v) {
        SmaroWindingMachineActivity.canHandStack.registerWriteFailedListener(this);
        SmaroWindingMachineActivity.canHandStack.registerWriteSucceedListener(this);
        switch (v.getId()) {
            case R.id.moving_speed_btn: {
                final String[] content = getResources().getStringArray(R.array.moving_speed);
                ListDialogFragment listDialog = new ListDialogFragment();
                Bundle bd = new Bundle();
                bd.putStringArray(ListDialogFragment.ARRAY, content);
                listDialog.setArguments(bd);
                listDialog.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        moving_speed_value.setText(content[position]);
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(sp.createCanCmd75(0x75, 0x01, 509, String.valueOf(position)));
                        sp.setValue(MachineParameterSharedPreference.MOVING_SPEED, String.valueOf(position));
                    }
                });
                listDialog.show(getFragmentManager(), "listDialog");
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void writeSucceed(ProtocolStack ps, byte[] request) {
        short index = (short) (request[2] & 0xff);
        if (index == 0x39) {
            SmaroWindingMachineActivity.canHandStack.unregisterWriteFailedListener(this);
            SmaroWindingMachineActivity.canHandStack.unregisterWriteSucceedListener(this);
            sp.setValue(index, request);
        }
        updateViews();
    }

    @Override
    public void writeFailed(ProtocolStack ps, byte[] request) {
        updateViews();
    }

}

